package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wswdkl
 * @version 1.0
 * @date 2022/2/11 10:24
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private LogService logService;

    /**
     * 分页查询供应商列表
     * @param page
     * @param rows
     * @param supplierName
     * @return
     */
    @Override
    public Map<String, Object> querySupplierPage(Integer page, Integer rows, String supplierName) {
        Map<String, Object> map = new HashMap<>();

        int total = supplierDao.getSupplierCount(supplierName);
        page = (page == 0 ? 1 : page);
        int offSet = (page - 1) * rows;
        List<Supplier> suppliers = supplierDao.querySupplierPage(offSet, rows, supplierName);

        logService.save(new Log(Log.SELECT_ACTION, "分页查询角色信息"));

        map.put("total", total);
        map.put("rows", suppliers);

        return map;
    }

    /**
     * 添加或者修改供应商信息
     * @param supplier
     * @return
     */
    @Override
    public boolean saveSupplier(Supplier supplier) {
        //根据supplier是否有supplierId，可以判断是添加还是修改
        if(supplier.getSupplierId() == null) {
            //a.代表是添加
            int insert = supplierDao.insertSupplier(supplier);
            if(insert >= 1) {
                logService.save(new Log(Log.INSERT_ACTION, "添加供应商信息"));
                return true;
            }
        } else {
            //b.代表为修改
            int update = supplierDao.updateSupplier(supplier);
            if(update >= 1) {
                logService.save(new Log(Log.UPDATE_ACTION,"修改供应商信息"));
                return true;
            }
        }
        return false;
    }

    /**
     * 删除供应商信息
     * @param ids
     * @return
     */
    @Override
    public boolean deleteSupplier(String ids) {
        String[] idList = ids.split(",");
        int delete = supplierDao.deleteSupplier(idList);
        if(delete >= 1) {
            logService.save(new Log(Log.DELETE_ACTION,"删除供应商信息"));
            return true;
        }
        return false;
    }
}
